<template>
  <div class="edit_dashboard">
    <div class="common-title">
      {{ ruleForm.name }}
    </div>
    <a-form-model ref="formRef" :model="ruleForm" :rules="rules" style="width: 80%">
      <a-form-model-item label="Channel" prop="channels">
        <a-select
          mode="multiple"
          v-model="ruleForm.channels"
          size="large"
          @change="handleChangeChannels"
          style="width: 60%"
        >
          <a-select-option v-for="item in channelOptions" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
        <a-tooltip placement="right">
          <template #title>
           We use channels info to find participants, and won't publish message to them
          </template>
          <svg
            style="margin-left: 12px"
            t="1650183344901"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="2589"
            width="16"
            height="16"><path d="M512 938.666667c235.648 0 426.666667-191.018667 426.666667-426.666667S747.648 85.333333 512 85.333333 85.333333 276.352 85.333333 512s191.018667 426.666667 426.666667 426.666667z m0 85.333333C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z" fill="#8a8a8a" p-id="2590"></path><path d="M520.96 232.106667c-62.293333 0-111.786667 17.92-147.626667 54.613333-36.693333 35.84-54.613333 84.48-54.613333 146.773333h90.453333c0-37.546667 7.68-67.413333 23.04-87.893333 17.066667-23.893333 45.226667-35.84 83.626667-35.84 30.72 0 54.613333 8.533333 71.68 25.6 16.213333 17.066667 24.746667 40.106667 24.746667 69.973333 0 22.186667-7.68 42.666667-23.04 62.293334l-14.506667 16.213333c-52.906667 46.933333-85.333333 81.92-97.28 105.813333-11.093333 22.186667-16.213333 49.493333-16.213333 81.066667v14.506667h91.306666v-14.506667c0-21.333333 4.266667-40.106667 13.653334-57.173333 7.68-15.36 19.626667-29.866667 34.986666-43.52 40.96-34.986667 64.853333-57.173333 72.533334-66.56 20.48-27.306667 31.573333-62.293333 31.573333-104.106667 0-51.2-17.066667-92.16-50.346667-122.026667-34.133333-30.72-78.506667-45.226667-133.973333-45.226666z m-14.506667 499.2c-17.92 0-32.426667 5.12-43.52 17.066666-12.8 11.093333-18.773333 25.6-18.773333 43.52 0 17.066667 5.973333 31.573333 18.773333 43.52 11.093333 11.946667 25.6 17.92 43.52 17.92 17.066667 0 32.426667-5.973333 45.226667-17.066666 11.946667-11.946667 17.92-26.453333 17.92-44.373334 0-17.92-5.973333-32.426667-17.92-43.52-11.946667-11.946667-27.306667-17.066667-45.226667-17.066666z" fill="#8a8a8a" p-id="2591"></path></svg>
        </a-tooltip>
      </a-form-model-item>
      <a-form-model-item label="Participants" prop="invited_participants">
        <a-select
          mode="multiple"
          v-model="ruleForm.invited_participants"
          size="large"
          style="width: 90%"
          :filter-option="false"
          @change="searchParticipants"
          placeholder="Add participants..."
        >
          <a-select-option v-for="item in participantsOptions" :key="item.ref_user_id" :value="item.ref_user_id">{{ item.profile.real_name }}</a-select-option>
        </a-select>
        <a-tooltip placement="right">
          <template #title>
            The participants are members from above channel list
          </template>
          <svg
            style="margin-left: 12px"
            t="1650183344901"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="2589"
            width="16"
            height="16"><path d="M512 938.666667c235.648 0 426.666667-191.018667 426.666667-426.666667S747.648 85.333333 512 85.333333 85.333333 276.352 85.333333 512s191.018667 426.666667 426.666667 426.666667z m0 85.333333C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z" fill="#8a8a8a" p-id="2590"></path><path d="M520.96 232.106667c-62.293333 0-111.786667 17.92-147.626667 54.613333-36.693333 35.84-54.613333 84.48-54.613333 146.773333h90.453333c0-37.546667 7.68-67.413333 23.04-87.893333 17.066667-23.893333 45.226667-35.84 83.626667-35.84 30.72 0 54.613333 8.533333 71.68 25.6 16.213333 17.066667 24.746667 40.106667 24.746667 69.973333 0 22.186667-7.68 42.666667-23.04 62.293334l-14.506667 16.213333c-52.906667 46.933333-85.333333 81.92-97.28 105.813333-11.093333 22.186667-16.213333 49.493333-16.213333 81.066667v14.506667h91.306666v-14.506667c0-21.333333 4.266667-40.106667 13.653334-57.173333 7.68-15.36 19.626667-29.866667 34.986666-43.52 40.96-34.986667 64.853333-57.173333 72.533334-66.56 20.48-27.306667 31.573333-62.293333 31.573333-104.106667 0-51.2-17.066667-92.16-50.346667-122.026667-34.133333-30.72-78.506667-45.226667-133.973333-45.226666z m-14.506667 499.2c-17.92 0-32.426667 5.12-43.52 17.066666-12.8 11.093333-18.773333 25.6-18.773333 43.52 0 17.066667 5.973333 31.573333 18.773333 43.52 11.093333 11.946667 25.6 17.92 43.52 17.92 17.066667 0 32.426667-5.973333 45.226667-17.066666 11.946667-11.946667 17.92-26.453333 17.92-44.373334 0-17.92-5.973333-32.426667-17.92-43.52-11.946667-11.946667-27.306667-17.066667-45.226667-17.066666z" fill="#8a8a8a" p-id="2591"></path></svg>
        </a-tooltip>
      </a-form-model-item>
      <div style="display: flex;justify-content:space-between;">
        <a-form-model-item label="Start date" style="width: 48%" prop="start_time">
          <a-date-picker show-time size="large" format="MMM DD,YYYY, hh:mm A" v-model="ruleForm.start_time" @change="handleChangeStartTime" style="width: 100%"/>
        </a-form-model-item>
        <a-form-model-item label=" Release date" style="width: 48%" prop="release_time">
          <a-date-picker show-time size="large" format="MMM DD,YYYY, hh:mm A" v-model="ruleForm.release_time" @change="handleChangeReleaseTime" style="width: 100%"/>
        </a-form-model-item>
      </div>
      <div style="display: flex;justify-content:space-between;">
        <a-form-model-item label="Timezone" prop="timezone" style="width: 48%">
          <a-select
            allowClear
            showSearch
            v-model="ruleForm.timezone"
            size="large"
            style="width: 100%"
          >
            <a-select-option v-for="item in timezoneOptions" :key="item.timezone" :value="item.timezone">{{ item.display_name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="Can other participants see the report?" prop="report_shareable" style="width: 48%">
          <a-select
            v-model="ruleForm.report_shareable"
            size="large"
            style="width: 100%"
          >
            <a-select-option :value="1">YES</a-select-option>
            <a-select-option :value="0">NO</a-select-option>
          </a-select>
        </a-form-model-item>
      </div>
      <div style="display: flex;justify-content:space-between;">
        <a-form-model-item label="Anonymous" prop="anonymous" style="width: 48%">
          <a-select
            v-model="ruleForm.anonymous"
            size="large"
            style="width: 100%"
          >
            <a-select-option :value="1">YES</a-select-option>
            <a-select-option :value="0">NO</a-select-option>
          </a-select>
        </a-form-model-item>
      </div>
      <div style="text-align: right">
        <a-button @click="handleback" size="large">PREVIOUS</a-button>
        <a-button style="margin-left: 38px" type="primary" size="large" @click="handleSubmit">SAVE</a-button>
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { ideaDashboard, ideaSetting } from '@/api/api'
import dayjs from 'dayjs'
console.log()
export default {
  name: 'Edit',
  data () {
    const validateTime1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input the start time'))
      } else if (dayjs(value) <= dayjs().add(5, 'minute')) {
        callback(new Error("Ideation start time needs to at least 5 minutes from now"))
      }
      else if (dayjs(value) >= dayjs(this.ruleForm.release_time)) {
        callback(new Error("Release date needs to be at least 5 minutes from start date"))
      } else {
        callback()
      }
    }
    const validateTime2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input the release time'))
      } else if (dayjs(value) <= dayjs(this.ruleForm.start_time)) {
        callback(new Error("Release date needs to be at least 5 minutes from start date"))
      } else {
        callback()
      }
    }
    const validatorChannels = (rule, value, callback) => {
      console.log('value', value)
      if (value === '') {
        callback(new Error('Please select channels to find participants'))
      } else if (value.length === 0) {
        callback(new Error('Please select channels to find participants'))
      } else {
        callback()
      }
    }
    const validatorParticioants = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please select at least one participant'))
      } else if (value.length === 0) {
        callback(new Error('Please select at least one participant'))
      } else {
        callback()
      }
    }
    return {
      ideaId: '',
      ruleForm: {
        name: '',
        description: '',
        start_time: null,
        release_time: null,
        timezone: '',
        channels: [],
        invited_participants: [],
        report_shareable: 1,
        anonymous: 0,
        questions: []
      },
      rules: {
        timezone: [{ required: true }],
        channels: [{ required: true, validator: validatorChannels }],
        report_shareable: [{ required: true }],
        invited_participants: [{ required: true, validator: validatorParticioants }],
        start_time: [{ required: true, validator: validateTime1, trigger: 'change' }],
        release_time: [{ required: true, validator: validateTime2, trigger: 'change' }]
      },
      channelOptions: [
      ],
      participantsOptions: [],
      timezoneOptions: [
      ]
    }
  },
  created () {
    this.initIdeation()
    this.getChannels()
    this.getTimezones()
  },
    methods: {
    initIdeation () {
      const { id, questionForm,formDetail } = this.$route.query
      console.log('this.$route.query',this.$route.query.formDetail);
      if (questionForm) {
        console.log('questionForm', questionForm)
        // 创建idea
        this.ruleForm.name = questionForm.name
        this.ruleForm.questions = questionForm.questions
        this.ruleForm.description = questionForm.description
      }
      console.log('this.ruleForm', this.ruleForm)
      if (id) {
        this.ideaId = id
        // 编辑idea
        ideaDashboard.read(id).then(res => {
          console.log(res)
          const data = res.idea_definition
          // 回显示数据
          this.ruleForm.channels = data.channels.map(el => el.channel_id)
          this.ruleForm.invited_participants = data.invited_participants.map(el => el.ref_user_id)
          this.handleChangeChannels(this.ruleForm.channels)
          this.ruleForm.start_time = data.timer.start_time
          this.ruleForm.release_time = data.timer.release_time
          this.ruleForm.timezone = data.timezone
          this.ruleForm.report_shareable = data.report_shareable ? 1 : 0
          this.ruleForm.anonymous = data.anonymous ? 1 : 0
        })
      }

      if (formDetail) {
          console.log('formDetail',formDetail)
          // 回显示数据
          this.ruleForm.channels = formDetail.channels
          this.ruleForm.invited_participants = formDetail.invited_participants
          this.handleChangeChannels(this.ruleForm.channels)
          this.ruleForm.start_time = formDetail.start_time
          this.ruleForm.release_time = formDetail.release_time
          this.ruleForm.timezone = formDetail.timezone
          this.ruleForm.report_shareable = formDetail.report_shareable 
          this.ruleForm.anonymous = formDetail.anonymous
      }
    },
    getChannels () {
      ideaDashboard.getChannels().then(res => {
        this.channelOptions = res.channels
        console.log('this.channelOptions', this.channelOptions)
      })
    },
    handleChangeChannels (ids) {
      console.log(ids)
      if (!ids || !ids.length) {
        this.ruleForm.invited_participants = []
        this.participantsOptions = []
        return
      }
      ideaDashboard.getUsers(ids.join(',')).then(res => {
        this.participantsOptions = res.users
      })
    },
    getTimezones () {
      ideaSetting.timezonesList().then(res => {
        this.timezoneOptions = res.timezones
        console.log('this.timezoneOptions ', this.timezoneOptions)
      })
    },
    searchParticipants () {

    },
    handleChangeStartTime (date, dateString) {
      console.log(date,dateString)
      this.ruleForm.start_time = date.format('YYYY-MM-DD HH:mm:ss')
    },
    handleChangeReleaseTime (date, dateString) {
      console.log(dateString)
      this.ruleForm.release_time = date.format('YYYY-MM-DD HH:mm:ss')
    },
    handleSubmit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const channels = this.channelOptions.filter(el => this.ruleForm.channels.indexOf(el.id) > -1).map(el => {
            return {
              'category': 'slack',
              'channel_id': el.id,
              'name': el.name,
              'ref_team_id': ''
            }
          })
          // eslint-disable-next-line camelcase
          const invited_participants = this.participantsOptions.filter(el => this.ruleForm.invited_participants.indexOf(el.ref_user_id) > -1).map(el => {
            return {
              'category': 'slack',
              'email': el.email,
              'name': el.profile.real_name,
              'ref_team_id': el.ref_team_id,
              'ref_user_id': el.ref_user_id
            }
          })
          const formData = {
            name: this.ruleForm.name,
            timer: {
              'start_time': this.ruleForm.start_time,
              'release_time': this.ruleForm.release_time
            },
            timezone: this.ruleForm.timezone,
            channels,
            invited_participants,
            questions: this.ruleForm.questions.filter(el => el.content),
            report_shareable: !!this.ruleForm.report_shareable,
            anonymous: !!this.ruleForm.anonymous
          }
          if (this.ideaId) {
            ideaDashboard.update(this.ideaId, { ...formData }).then(res => {
              this.$notification.success({
                message: 'Your ideation is saved successfully!'
              })
              this.$router.replace('/Dashboard')
            })
          } else {
            ideaDashboard.create({ ...formData }).then(res => {
              this.$notification.success({
                message: 'Your ideation is saved successfully!'
              })
              this.$router.replace('/Dashboard')
            })
          }
        }
      })
    },
    handleback () {
      if (this.ideaId) {
        this.$router.replace({
          path: '/Dashboard/edit',
          query: {
            id: this.ideaId,
            questionForm: {
              name: this.ruleForm.name,
              questions: this.ruleForm.questions,
              description: this.ruleForm.description
            }
          }
        })

      } else {
        this.$router.replace({
          path: '/Dashboard/create',
          query: {
            questionForm: {
              name: this.ruleForm.name,
              questions: this.ruleForm.questions,
              description: this.ruleForm.description
            },
            formDetail: {
              ...this.ruleForm
            }
          },
          
        })
      }
    }
  }
}
</script>

<style scoped lang='less'>
.edit_dashboard {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  min-height: 100%;
  padding: 24px 84px;
  background-color: #FFFFFF;
  z-index: 999;
  .common-title {
    margin-bottom: 20px;
  }
  ::v-deep .ant-form {
    .ant-form-item label {
      color: #5E6366;
      font-size: 16px;
      font-weight: 400;
    }
  }
}
</style>
